package com.huilian.iotbox.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huilian.iotbox.admin.dao.CommodityStockDao;
import com.huilian.iotbox.admin.service.CommodityStockService;
import com.huilian.iotbox.data.common.ServerResponse;
import com.huilian.iotbox.data.dto.CommodityStockRecordDto;
import com.huilian.iotbox.data.enums.RoleEnum;
import com.huilian.iotbox.data.properties.ConfigProperties;
import com.huilian.iotbox.data.properties.FileProperties;
import com.huilian.iotbox.data.vo.CommodityStockVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Font;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author LinYinDong
 * @date 2024/9/14 下午3:05
 */
@Service
@Slf4j
public class CommodityStockServiceImpl implements CommodityStockService {

    @Autowired
    private FileProperties fileProperties;
    @Autowired
    private CommodityStockDao commodityStockDao;
    @Autowired
    public ConfigProperties configProperties;

    @Override
    public PageInfo findCommodityStockList(CommodityStockRecordDto commodityStockRecordDto) {
        commodityStockRecordDto.setType(2);
        PageHelper.orderBy("cs.createTime desc");
        PageHelper.startPage(commodityStockRecordDto.getPageNum(), commodityStockRecordDto.getPageSize(), true);
        List<CommodityStockVo> list = commodityStockDao.findCommodityStockList(commodityStockRecordDto);
        for (CommodityStockVo commodityStockVo : list) {
            commodityStockVo.setTotalStockCostPrice(commodityStockVo.getCostPrice().multiply(BigDecimal.valueOf(commodityStockVo.getStock())));
            commodityStockVo.setTotalSalePriceSum(commodityStockVo.getRetailPrice().multiply(BigDecimal.valueOf(commodityStockVo.getStock())));
        }
        PageInfo pageInfo = new PageInfo(list);
        return pageInfo;
    }

    @Override
    public ServerResponse exportCommodityStockList(CommodityStockRecordDto commodityStockRecordDto) {
        commodityStockRecordDto.setType(2);
        List<CommodityStockVo> list = commodityStockDao.findCommodityStockList(commodityStockRecordDto);
        if (StringUtils.isEmpty(list) || list.size() <= 0) {
            return ServerResponse.createByErrorMessage("没有数据可以导出");
        }
        for (CommodityStockVo commodityStockVo : list) {
            commodityStockVo.setTotalStockCostPrice(commodityStockVo.getCostPrice().multiply(BigDecimal.valueOf(commodityStockVo.getStock())));
            commodityStockVo.setTotalSalePriceSum(commodityStockVo.getRetailPrice().multiply(BigDecimal.valueOf(commodityStockVo.getStock())));
        }
        String[] headers = new String[]{"商品", "供应商", "运营商", "安全库存", "库存数", "成本价", "售价", "库存总额", "售价总额", "条形码", "商品类型"};

        String sheetName = "";
        if (RoleEnum.SUPER_ADMINISTRATOR.getRoleId() != commodityStockRecordDto.getUserInfo().getRoleId()) {
            sheetName = commodityStockRecordDto.getUserInfo().getUsername() + "库存管理记录";
        } else {
            sheetName = "库存管理记录";
        }
        sheetName = sheetName + System.currentTimeMillis();
        // 创建了一个excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet(sheetName);
        sheet.setDefaultColumnWidth(10);
        sheet.setColumnWidth(0, 30 * 256);
        sheet.setColumnWidth(1, 30 * 256);
        sheet.setColumnWidth(2, 25 * 256);
        sheet.setColumnWidth(3, 25 * 256);
        sheet.setColumnWidth(8, 25 * 256);
//        sheet.createFreezePane(0, 4, 0, 4);
        //标题样式
        HSSFCellStyle titleStyle = wb.createCellStyle(); // 样式对象
        //设置标题字体格式
        Font font = wb.createFont();
        //设置字体样式
        //font.setFontHeightInPoints((short) 20);   //--->设置字体大小
        font.setFontName("Courier New");   //---》设置字体，是什么类型例如：宋体
        font.setItalic(true);     //--->设置是否是加粗
        titleStyle.setFont(font);     //--->将字体格式加入到style1中
        titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平
        titleStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); //垂直

        //内容样式
        HSSFCellStyle contextStyle = wb.createCellStyle(); // 样式对象
        //设置标题字体格式
        Font contextfont = wb.createFont();
        contextfont.setFontHeightInPoints((short) 13);   //--->设置字体大小
        //设置字体样式
        contextStyle.setFont(contextfont);     //--->将字体格式加入到style1中
        contextStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平
        contextStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); //垂直
        contextStyle.setWrapText(true);//设置自动换行

        //表格第一行
        HSSFRow row1 = sheet.createRow(0);   //--->创建一行
        row1.setHeightInPoints(20);
        HSSFCell cell1 = row1.createCell(0);   //--->创建一个单元格
        // cell1.setCellStyle(titleStyle);
        cell1.setCellValue("代币记录");
        //表格第二行
        HSSFRow r2 = sheet.createRow(1);
        r2.setHeightInPoints(20);
        HSSFCell c2 = r2.createCell(0);

        //标题
        HSSFRow row2 = sheet.createRow(3);           //--->创建一行
        contextStyle.setFillForegroundColor(HSSFColor.LEMON_CHIFFON.index);// 设置背景色
        contextStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        contextStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
        contextStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
        contextStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
        contextStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
        contextfont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//粗体显示
        contextStyle.setFont(contextfont);
        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell2 = row2.createCell(i);
            cell2.setCellValue(headers[i]);
            cell2.setCellStyle(contextStyle);
        }
        int index = 0;//记录额外创建的sheet数量
        int j = 0;
        // 循环每行
        for (int i = 4; i < list.size() + 4; i++) {
            if ((i) % 65500 == 0) {
                sheet = wb.createSheet("salesList" + index);
                index++;
            }
            // 创建行
            HSSFRow row = sheet.createRow((i) - (index * 65500));
            // 创建列

            //商品
            HSSFCell contextCell0 = row.createCell(0);
            if (!StringUtils.isEmpty(list.get(j).getGoodsName())) {
                contextCell0.setCellValue(list.get(j).getGoodsName());
            } else {
                contextCell0.setCellValue("");
            }
            //供应商
            HSSFCell contextCell1 = row.createCell(1);
            if (!StringUtils.isEmpty(list.get(j).getFullName())) {
                contextCell1.setCellValue(list.get(j).getFullName());
            } else {
                contextCell1.setCellValue("");
            }

            //运营商
            String userName = "";
            HSSFCell contextCell2 = row.createCell(2);
            if (!StringUtils.isEmpty(list.get(j).getName())) {
                userName = list.get(j).getName() + ":";
                contextCell2.setCellValue(list.get(j).getName());
            } else {
                contextCell2.setCellValue("");
            }
            if (!StringUtils.isEmpty(list.get(j).getUserName())) {
                contextCell2.setCellValue(userName + list.get(j).getUserName());
            }

            //安全库存
            HSSFCell contextCell3 = row.createCell(3);
            if (!StringUtils.isEmpty(list.get(j).getSafeStock())) {
                contextCell3.setCellValue(list.get(j).getSafeStock());
            } else {
                contextCell3.setCellValue(0);
            }

            //库存
            HSSFCell contextCell4 = row.createCell(4);
            if (!StringUtils.isEmpty(list.get(j).getSafeStock())) {
                contextCell4.setCellValue(list.get(j).getSafeStock());
            } else {
                contextCell4.setCellValue(0);
            }

            //成本价
            HSSFCell contextCell5 = row.createCell(5);
            if (!StringUtils.isEmpty(list.get(j).getCostPrice())) {
                contextCell5.setCellValue(list.get(j).getCostPrice().toString());
            } else {
                contextCell5.setCellValue("");
            }
            //售价
            HSSFCell contextCell6 = row.createCell(6);
            if (!StringUtils.isEmpty(list.get(j).getRetailPrice())) {
                contextCell6.setCellValue(list.get(j).getRetailPrice().toString());
            } else {
                contextCell6.setCellValue("");
            }
            //库存总额
            HSSFCell context1Cell7 = row.createCell(7);
            if (!StringUtils.isEmpty(list.get(j).getTotalStockCostPrice())) {
                context1Cell7.setCellValue(list.get(j).getTotalStockCostPrice().toString());
            } else {
                context1Cell7.setCellValue("");
            }
            //售价总额
            HSSFCell contextCell8 = row.createCell(8);
            if (!StringUtils.isEmpty(list.get(j).getTotalSalePriceSum())) {
                contextCell8.setCellValue(list.get(j).getTotalSalePriceSum().toString());
            } else {
                contextCell8.setCellValue("");
            }

            //条形码
            HSSFCell contextCell9 = row.createCell(9);
            if (!StringUtils.isEmpty(list.get(j).getBarCode())) {
                contextCell9.setCellValue(list.get(j).getBarCode());
            } else {
                contextCell9.setCellValue(0);
            }

            //商品类型
            HSSFCell contextCell10 = row.createCell(10);
            if (!StringUtils.isEmpty(list.get(j).getGroupName())) {
                contextCell10.setCellValue(list.get(j).getGroupName());
            } else {
                contextCell10.setCellValue(0);
            }

            j++;
            if (j >= list.size()) {
                j = 0;
            }
        }
        // 保存文件
        FileOutputStream fileOut = null;
        String fileName = fileProperties.getSaveImgPath() + "/" + sheetName + ".xls";

        try {
            File f = new File(fileName);
            if (!f.exists()) {
                f.createNewFile();
            }
            // 文件保存的地址和名称
            log.info("------------------------------iot后台库存管理导出:" + fileName);
            fileOut = new FileOutputStream(fileName);
            wb.write(fileOut);

        } catch (IOException e) {
            // 处理文件操作可能发生的IO异常
            e.printStackTrace();
            return ServerResponse.createByErrorMessage("文件保存失败:" + e + fileProperties.getSaveImgPath());
        } catch (Exception e) {
            // 其他异常
            e.printStackTrace();
            return ServerResponse.createByErrorMessage("文件保存过程中发生了错误:" + e);

        } finally {
            // 关闭流
            if (fileOut != null) {
                try {
                    fileOut.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        Map<String, String> map = new HashMap<>();
        map.put("fileName", sheetName + ".xls");
        map.put("downloadUrl", configProperties.getAdminBackEndUrl() + "/api/fileExport/download/" + sheetName + ".xls");
        return ServerResponse.createBySuccess(map);
    }
}
